package com.cyj.dream.admin.controller.admin.system;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cyj.dream.admin.contacts.enums.ContactsBusinessTypesEnum;
import com.cyj.dream.admin.model.request.SysContactsQueryRequest;
import com.cyj.dream.admin.model.system.SysContacts;
import com.cyj.dream.admin.service.system.SysContactsService;
import com.cyj.dream.admin.util.IsEmptyUtils;
import com.cyj.dream.core.aspect.annotation.ResponseResult;
import com.cyj.dream.core.aspect.annotation.log.LogRecord;
import com.cyj.dream.core.aspect.enums.OperatorType;
import com.cyj.dream.core.constant.Constant;
import com.cyj.dream.core.constant.enums.ResultCode;
import com.cyj.dream.core.constant.pagemodel.PageParam;
import com.cyj.dream.core.constant.pagemodel.Response;
import com.cyj.dream.core.exception.BizException;
import com.cyj.dream.core.util.file.EasyExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 通讯录控制器模块
 * @BelongsProject: fckj-restaurant
 * @BelongsPackage: com.fckj.fckjrestaurant.controller.admin.systems
 * @Author: ChenYongJia
 * @CreateTime: 2021-05-20 08:53
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
@RestController
@ResponseResult
@Api(value = "contacts", tags = "通讯录模块")
@RequestMapping(value = "/pc/contacts", name = "通讯录模块")
public class SysContactsController {

    @Autowired
    private SysContactsService sysContactsService;

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    /**
     * 分页查询通讯录信息
     *
     * @param pageParam 用户信息入参请求信息
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @date 2021/5/20 9:54
     * @author ChenYongJia
     * @version 1.0
     */
    @ApiOperation(value = "分页查询通讯录信息", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageParam", value = "通讯录查询request", dataType = "PageParam<SysContactsQueryRequest>", required = true)
    })
    @LogRecord(title = "分页查询通讯录信息", operatetype = OperatorType.SELECT)
    @RequestMapping(value = "/selectSysContacts", name = "分页查询通讯录信息", method = RequestMethod.POST)
    public Map<String, Object> selectSysContacts(@RequestBody PageParam<SysContactsQueryRequest> pageParam) {
        log.info("进入分页查询通讯录信息方法控制器，参数为 pageParam：{}", JSONObject.toJSONString(pageParam));
        if (IsEmptyUtils.isEmpty(pageParam.getPageNum()) || IsEmptyUtils.isEmpty(pageParam.getPageSize())) {
            log.error("出现错误：方法执行失败失败！参数为空，请检查参数后重新提交！");
            throw new BizException(ResultCode.PARAM_NOT_COMPLETE);
        }

        Map<String, Object> map = new HashMap<>(Constant.INITIAL_CAPACITY);

        IPage<SysContacts> sysContactsList = sysContactsService.list(pageParam);

        List<SysContacts> sysContacts = sysContactsList.getRecords();
        if (!IsEmptyUtils.isEmpty(sysContacts)) {
            sysContacts.stream().forEach(item -> {
                // todo 根据项目 id 查询项目信息 item.getSysContactsAge()
                item.setSysContactsInProjectName("");
                item.setSysContactsBusinessTypes(ContactsBusinessTypesEnum.getMessByCode(Integer.parseInt(item.getSysContactsBusinessTypes())));
            });
            sysContactsList.setRecords(sysContacts);
        }

        map.put("list", sysContactsList.getRecords());
        return map;
    }

    /**
     * 根据通讯录id查询通讯录信息
     *
     * @param sysContacts 通讯录对象
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @date 2021-5-20 09:02:19
     * @author ChenYongJia
     * @version 1.0
     */
    @ApiOperation(value = "根据通讯录id查询通讯录信息", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysContacts", value = "通讯录对象", dataType = "SysContacts", required = true)
    })
    @LogRecord(title = "根据通讯录id查询通讯录信息", operatetype = OperatorType.SELECT)
    @RequestMapping(value = "/selectBySysContacts", name = "根据通讯录id查询通讯录信息", method = RequestMethod.POST)
    public Map<String, Object> selectBySysContacts(@RequestBody SysContacts sysContacts) {
        log.info("进入根据通讯录id查询通讯录信息控制器方法，参数为：{}", JSONObject.toJSONString(sysContacts));
        Map<String, Object> map = new HashMap<>(Constant.INITIAL_CAPACITY);
        if (IsEmptyUtils.isEmpty(sysContacts.getDreamId())) {
            log.error("出现错误：方法执行失败失败！参数为空，请检查参数后重新提交！");
            throw new BizException(ResultCode.PARAM_NOT_COMPLETE);
        }

        map.put("info", sysContactsService.selectBySysContactsId(sysContacts));
        return map;
    }

    /**
     * 添加通讯录信息
     *
     * @param sysContacts 通讯录对象
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @date 2021-5-20 08:56:39
     * @author ChenYongJia
     * @version 1.0
     */
    @ApiOperation(value = "添加通讯录信息", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysContacts", value = "通讯录对象", dataType = "SysContacts", required = true)
    })
    @LogRecord(title = "添加通讯录信息", operatetype = OperatorType.INSERT)
    @RequestMapping(value = "/addSysContacts", name = "添加通讯录信息", method = RequestMethod.POST)
    public Map<String, Object> addSysContacts(@RequestBody SysContacts sysContacts) {
        log.info("进入添加通讯录信息控制器方法，参数为：{}", JSONObject.toJSONString(sysContacts));
        Map<String, Object> map = new HashMap<>(Constant.INITIAL_CAPACITY);
        this.checkData(sysContacts);

        map.put("info", sysContactsService.addSysContacts(sysContacts));
        return map;
    }

    /**
     * 获取通讯录人员业务类型枚举值
     *
     * @return java.util.Map<java.lang.Object, java.lang.String>
     * @date 2021/6/22 10:53
     * @author ChenYongJia
     * @version 1.0
     */
    @ApiOperation(value = "获取通讯录人员业务类型枚举值", httpMethod = "GET")
    @LogRecord(title = "获取通讯录人员业务类型枚举值", operatetype = OperatorType.SELECT)
    @RequestMapping(value = "/getConBusType", name = "获取通讯录人员业务类型枚举值", method = RequestMethod.GET)
    public List<Map<String, Object>> getConBusType() {
        log.info("进入获取通讯录人员业务类型枚举值控制器方法");

        List<Map<String, Object>> mapList = new ArrayList<>();
        /*Arrays.asList(ContactsBusinessTypesEnum.values()).forEach(day -> {
            Map<String, Object> map = new HashMap<>();
            map.put("key", day.getCode());
            map.put("value", day.getMessage());
            mapList.add(map);
        });*/

        for (ContactsBusinessTypesEnum type : ContactsBusinessTypesEnum.values()) {
            Map<String, Object> map = new HashMap<>(Constant.INITIAL_CAPACITY);
            map.put("key", type.getCode());
            map.put("value", type.getMessage());
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 修改通讯录信息
     *
     * @param sysContacts 通讯录对象
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @date 2021-5-20 09:02:24
     * @author ChenYongJia
     * @version 1.0
     */
    @ApiOperation(value = "修改通讯录信息", httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysContacts", value = "通讯录对象", dataType = "SysContacts", required = true)
    })
    @LogRecord(title = "修改通讯录信息", operatetype = OperatorType.UPDATE)
    @RequestMapping(value = "/updateSysContacts", name = "修改通讯录信息", method = RequestMethod.PUT)
    public Map<String, Object> updateSysContacts(@RequestBody SysContacts sysContacts) {
        log.info("进入修改通讯录信息控制器方法，参数为：{}", JSONObject.toJSONString(sysContacts));
        Map<String, Object> map = new HashMap<>(Constant.INITIAL_CAPACITY);
        if (IsEmptyUtils.isEmpty(sysContacts.getDreamId())) {
            log.error("出现错误：方法执行失败失败！参数为空，请检查参数后重新提交！");
            throw new BizException(ResultCode.PARAM_NOT_COMPLETE);
        }

        this.checkData(sysContacts);

        map.put("info", sysContactsService.updateSysContacts(sysContacts));
        return map;
    }


    /**
     * 修改通讯录信息--绑定项目
     *
     * @param sysContacts 通讯录对象
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @date 2021-5-20 09:02:24
     * @author ChenYongJia
     * @version 1.0
     */
    @ApiOperation(value = "修改通讯录信息--绑定项目", httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysContacts", value = "通讯录对象", dataType = "SysContacts", required = true)
    })
    @LogRecord(title = "修改通讯录信息--绑定项目", operatetype = OperatorType.UPDATE)
    @RequestMapping(value = "/updateSysContactsByProject", name = "修改通讯录信息--绑定项目", method = RequestMethod.PUT)
    public Map<String, Object> updateSysContactsByProject(@RequestBody SysContacts sysContacts) {
        log.info("进入修改通讯录信息控制器方法，参数为：{}", JSONObject.toJSONString(sysContacts));
        Map<String, Object> map = new HashMap<>(Constant.INITIAL_CAPACITY);
        if (IsEmptyUtils.isEmpty(sysContacts.getDreamId())) {
            log.error("出现错误：方法执行失败失败！参数为空，请检查参数后重新提交！");
            throw new BizException(ResultCode.PARAM_NOT_COMPLETE);
        }

        map.put("info", sysContactsService.updateSysContacts(sysContacts));
        return map;
    }

    /**
     * 删除通讯录信息
     *
     * @param sysContacts 通讯录对象
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @date 2021-5-20 09:02:27
     * @author ChenYongJia
     * @version 1.0
     */
    @ApiOperation(value = "删除通讯录信息", httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysContacts", value = "通讯录对象集合", dataType = "List<SysContacts>", required = true)
    })
    @LogRecord(title = "删除通讯录信息", operatetype = OperatorType.DELETE)
    @RequestMapping(value = "/deleteSysContacts", name = "删除通讯录信息", method = RequestMethod.DELETE)
    public Map<String, Object> deleteSysContacts(@RequestBody List<SysContacts> sysContacts) {
        log.info("进入添加通讯录信息控制器方法，参数为：{}", JSONObject.toJSONString(sysContacts));
        Map<String, Object> map = new HashMap<>(Constant.INITIAL_CAPACITY);
        if (IsEmptyUtils.isEmpty(sysContacts)) {
            log.error("出现错误：方法执行失败失败！参数为空，请检查参数后重新提交！");
            throw new BizException(ResultCode.PARAM_NOT_COMPLETE);
        }

        map.put("info", sysContactsService.deleteSysContacts(sysContacts));
        return map;
    }

    /**
     * 导出通讯录信息
     *
     * @param sysContactsName 通讯录请求入参
     * @param sysContactsBusinessTypes 通讯录请求入参
     * @param sysContactsStatus 通讯录请求入参
     * @param sysContactsCompany 通讯录请求入参
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @date 2021-5-20 09:02:27
     * @author ChenYongJia
     * @version 1.0
     */
    @ApiOperation(value = "导出通讯录信息", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "queryRequest", value = "通讯录请求入参", dataType = "SysContactsQueryRequest", required = true)
    })
    @LogRecord(title = "导出通讯录信息", operatetype = OperatorType.EXPORT)
    @RequestMapping(value = "/exportSysContacts", name = "导出通讯录信息", method = RequestMethod.GET)
    public Response exportSysContacts(HttpServletResponse response, @RequestParam(value = "sysContactsName", required = false) String sysContactsName,
                                      @RequestParam(value = "sysContactsBusinessTypes", required = false) String sysContactsBusinessTypes,
                                      @RequestParam(value = "sysContactsStatus", required = false) Integer sysContactsStatus,
                                      @RequestParam(value = "sysContactsCompany", required = false) String sysContactsCompany) {
        log.info("进入导出通讯录信息控制器方法，sysContactsName 参数为：{}，sysContactsBusinessTypes 参数为：{}，sysContactsStatus 参数为：{}，sysContactsCompany 参数为：{}，",
                sysContactsName, sysContactsBusinessTypes, sysContactsStatus, sysContactsCompany);
        SysContactsQueryRequest queryRequest = new SysContactsQueryRequest();
        if (!IsEmptyUtils.isEmpty(sysContactsName)) {
            queryRequest.setSysContactsName(sysContactsName);
        }
        if (!IsEmptyUtils.isEmpty(sysContactsBusinessTypes)) {
            queryRequest.setSysContactsBusinessTypes(sysContactsBusinessTypes);
        }
        if (!IsEmptyUtils.isEmpty(sysContactsStatus)) {
            queryRequest.setSysContactsStatus(sysContactsStatus);
        }
        if (!IsEmptyUtils.isEmpty(sysContactsCompany)) {
            queryRequest.setSysContactsCompany(sysContactsCompany);
        }
        List<SysContacts> sysContactsList = sysContactsService.allSysContactsByParam(queryRequest);

        String fileName = "ContactsList--" + FORMATTER.format(LocalDateTime.now());
        EasyExcelUtils.exportExcle(response, sysContactsList, fileName, SysContacts.class);
        return null;
    }

    /**
     * 导出通讯录信息模板文件
     *
     * @param response
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @date 2021-5-20 09:02:27
     * @author ChenYongJia
     * @version 1.0
     */
    @ApiOperation(value = "导出通讯录信息模板文件", httpMethod = "GET")
    @LogRecord(title = "导出通讯录信息模板文件", operatetype = OperatorType.EXPORT)
    @RequestMapping(value = "/exportSysContactsTemplate", name = "导出通讯录信息模板文件", method = RequestMethod.GET)
    public Response exportSysContactsTemplate(HttpServletResponse response) {
        log.info("进入导出通讯录信息模板文件控制器方法");
        List<SysContacts> sysContactsList = new ArrayList<>();
        SysContacts sysContacts = new SysContacts();
        sysContactsList.add(sysContacts);

        String fileName = "ContactsList--" + FORMATTER.format(LocalDateTime.now());
        EasyExcelUtils.exportExcle(response, sysContactsList, fileName, SysContacts.class);
        return null;
    }

    /**
     * 字段校验统一方法
     *
     * @param sysContacts
     * @return void
     * @date 2021/6/22 11:21
     * @author ChenYongJia
     * @version 1.0
     */
    private void checkData(SysContacts sysContacts) {
        if (IsEmptyUtils.isEmpty(sysContacts.getSysContactsName()) || IsEmptyUtils.isEmpty(sysContacts.getSysContactsCompany())
                || IsEmptyUtils.isEmpty(sysContacts.getSysContactsBusinessTypes()) || IsEmptyUtils.isEmpty(sysContacts.getSysContactsBirthday())
                || IsEmptyUtils.isEmpty(sysContacts.getSysContactsSex()) || IsEmptyUtils.isEmpty(sysContacts.getSysContactsAddress()) || IsEmptyUtils.isEmpty(sysContacts.getSysContactsSource())
                || IsEmptyUtils.isEmpty(sysContacts.getSysContactsPhone())) {
            log.error("出现错误：方法执行失败失败！参数为空，请检查参数后重新提交！");
            throw new BizException(ResultCode.PARAM_NOT_COMPLETE);
        }
    }

}
